package com.diaohaiwen.framework.mq.rocket;

import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 刁海文
 * @since 2024/1/16 20:45
 */
public class RocketService {

    @Resource
    DefaultMQProducer producer;

    public void send(String topic, String tags, Object data) {

        try {
            Message message = new Message(topic, tags, JSONObject.toJSONString(data).getBytes(StandardCharsets.UTF_8));
            producer.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(String topic, String tags, Object data, RocketDelayEnum delay) {

        try {
            Message message = new Message(topic, tags, JSONObject.toJSONString(data).getBytes(StandardCharsets.UTF_8));
            message.setDelayTimeLevel(delay.level);
            producer.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T> void send(String topic, String tags, Collection<T> datas) {
        List<Message> collect = datas.stream()
                .map(data -> new Message(topic, tags, JSONObject.toJSONString(data).getBytes(StandardCharsets.UTF_8)))
                .collect(Collectors.toList());
        try {
            producer.send(collect);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T> void send(String topic, String tags, Collection<T> datas,RocketDelayEnum delay) {
        List<Message> collect = datas.stream()
                .map(data -> {
                    Message message = new Message(topic, tags, JSONObject.toJSONString(data).getBytes(StandardCharsets.UTF_8));
                    message.setDelayTimeLevel(delay.level);
                    return message;
                })
                .collect(Collectors.toList());
        try {
            producer.send(collect);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
